// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// o [author] rhyme_lph
// a [email]  rhymelph@gmail.com
// k [github] https://github.com/rhymelph

import 'dart:convert';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/biometrics_data_entity.dart';
import 'package:finance_app/src/entities/user_profile_entity.dart';
import 'package:finance_app/src/http_service/http_user_service.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/page/login/create_account_page.dart';
import 'package:local_auth/local_auth.dart';

class CreateAccountProvider extends BaseProvider {
  TextEditingController fullNameController = TextEditingController();
  FocusNode fullNameFocusNode = FocusNode();

  TextEditingController passwordController = TextEditingController();
  FocusNode passwordFocusNode = FocusNode();
  bool enable = false;

  bool passwordError = false;

  bool showAuth = false;
  bool enableAuth = false;

  @override
  void dispose() {
    super.dispose();
    passwordController.dispose();
    fullNameController.dispose();
    fullNameFocusNode.dispose();
    passwordFocusNode.dispose();
  }

  @override
  void initState() {
    super.initState();
    passwordController.addListener(_onUpdateInput);
    fullNameController.addListener(_onUpdateInput);
    loadAuthentication();
  }

  void loadAuthentication() async {
    enableAuth = await LocalAuthentication().canCheckBiometrics;
  }

  @override
  Future get dataFuture => null;

  void _onUpdateInput() {
    if (passwordController.text.length > 0 &&
        fullNameController.text.length > 0) {
      if (enable == false) {
        enable = true;
        update();
      }
    } else {
      if (enable == true) {
        enable = false;
        update();
      }
    }
  }

  void onStartExploring() async {
    passwordFocusNode.unfocus();
    fullNameFocusNode.unfocus();
    String password = passwordController.text;
    if (password.length < 6) {
      passwordError = true;
      update();
      return;
    } else {
      passwordError = false;
      update();
    }
    String fullName = fullNameController.text;

    if (fullName.length == 0) {
      showToast(S.current.please_enter_full_name);
      return;
    }
    post(
        HttpUserService.updateMyProfile(
          name: fullName,
          password: password,
        ),
        autoHandler: AutoHandler.Toast,
        loadingTip: S.current.loading, onSuccess: (result) async {
      RProvider.myProvider.globalMap[ConfigKey.userProfile] =
          getEntityFromResult<UserProfileEntity>(result);
      await RProvider.myProvider.updateGlobalMap();
      if (enableAuth) {
        showAuth = true;
        update();
      } else {
        onSkipFirst();
      }
    });
  }

  void onSkipFirst() async {
    Config.biometricsData = BiometricsDataEntity()
      ..account = Config.userProfile.phoneNumber
      ..countryCode = Config.userProfile.countryCode
      ..password = passwordController.text;
    await RProvider.myProvider.updateGlobalMap();
    if (Config.userProfile.defaultCompanyId == null) {
      Routes.navigateTo(RouterGenProviders.createBusinessProfilePage,
          clearStack: true);
    } else {
      Routes.navigateTo(RouterGenProviders.dashboardPage, clearStack: true);
    }
  }

  void onEnableFingerprint() async {
    bool isSuccess = await LocalAuthentication()
        .authenticate(localizedReason: S.current.please_touch_fingerprint);
    if (isSuccess == true) {
      RProvider.myProvider.globalMap[ConfigKey.biometricsEnable] = true;
      onSkipFirst();
    }
  }
}
